import requests
import execjs
import time
import re


def get_cb():
    js_code = """
        function get_cb(){
            return "jQuery" + ("1.12.3" + Math.random()).replace(/\D/g, "")
        }
        return get_cb();
    """

    # 创建上下文
    ctx = execjs.compile(js_code)

    # 执行函数
    result = ctx.call("get_cb")
    return result


def get_wbp2u():
    js_code = """
        function get_wbp2u(){
          // D:\Development\python-project\spider\dongfang\get_requests\src\test\js\wbp2u.js
            const cookie = require("cookie");
            const cooks = require("../js/cooks.js");

            // 模拟浏览器的 document.cookie
            const cookieString = "qgqp_b_id=e5c15b302e908f9e9596bc1598ab11; websitepoptg_api_time=1733498615406; rskey=LAoksaTBnVnVzZ204UnJoVXlkS3ZTL0t5dz09zNzUM; isoutside=0; st_si=90576546761010; st_asi=delete; st_sn=18; st_psi=20241207165207945-113200301321-4029504020; st_pvi=13044721870445; st_sp=2024-12-03%2020%3A18%3A01; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink";
            const parsedCookies = cookie.parse(cookieString);

            // 重写 cooks.js 的 get 方法以使用 parsedCookies
            const browserCooks = {
              get(name) {
                return parsedCookies[name] || null;
              },
              set(key, value, expiredays, domain) {
                // 这里只是模拟设置 cookie，实际不会影响全局 cookie
                parsedCookies[key] = value;
              },
              del(key, domain) {
                delete parsedCookies[key];
              }
            };

            var delayparams = 'UID|0|MOBILE|0|web';

            if (browserCooks.get('uidal')) {
              delayparams = delayparams.replace('UID', browserCooks.get('uidal').substring(0, 16));
            } else {
              delayparams = delayparams.replace('UID', '');
            }

            if (browserCooks.get('mtp') != null) {
              if (browserCooks.get('mtp') == '0') {
                delayparams = delayparams.replace('MOBILE', '3');
              } else {
                delayparams = delayparams.replace('MOBILE', browserCooks.get('mtp'));
              }
            } else {
              delayparams = delayparams.replace('MOBILE', '0');
            }

            return delayparams
        }
        return get_wbp2u();
    """
    ctx = execjs.compile(js_code)
    result = ctx.call("get_wbp2u")
    return result

def get_gridlist():
    url = "http://quote.eastmoney.com/center/js/gridlist3.js"
    headers = {
        "accept": "*/*",
        "accept-encoding": "gzip, deflate",
        "accept-language": "zh-CN,zh;q=0.9",
        "connection": "keep-alive",
        "referer": "http://quote.eastmoney.com/center/gridlist.html?st=ChangePercent&sr=-1",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
    }

    response = requests.get(url)
    result = []
    if response.status_code == 200:
        ut = re.compile('ut: "(.*?)"').findall(response.text)
        fields = re.compile('fields: "(.*?)"').findall(response.text)
        for i in fields:
            if len(i) > 110:
                field = i
    else:
        result = None
        print("获取失败")
    result.append(ut[0])
    result.append(field)
    response.close()
    return result



def get_data(cb,wbp2u,ut,field):
    headers = {
        "accept": "*/*",
        "accept-encoding": "gzip, deflate",
        "accept-language": "zh-CN,zh;q=0.9",
        "connection": "keep-alive",
        "cookie": "qgqp_b_id=e5c1215b302e908f9e9596bc1598ab11; websitepoptg_api_time=1733498615406; rskey=LAoksaTBnVnVzZ204UnJoVXlkS3ZTL0t5dz09zNzUM; isoutside=0; st_si=90576546761010; st_asi=delete; st_sn=18; st_psi=20241207165207945-113200301321-4029504020; st_pvi=13044721870445; st_sp=2024-12-03%2020%3A18%3A01; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink",
        "host": "37.push2.eastmoney.com",
        "referer": "http://quote.eastmoney.com/center/gridlist.html?st=ChangePercent&sr=-1",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
    }

    params = [{
        "cb": "jQuery1124013757387089627393_1733561891364",
        "pn": i,
        "pz": 20,
        "po": 1,
        "np": 1,
        "ut": "bd1d9ddb04089700cf9c27f6f7426281",
        "fltt": 2,
        "invt": 2,
        "dect": 1,
        "wbp2u": "|0|0|0|web",
        "fid": "f3",
        "fs": "m:1+t:2,m:1+t:23",
        "fields": "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152",
        "_": int(time.time())
    } for i in range(1,121,1)]
    for param in params:
        url = "https://36.push2.eastmoney.com/api/qt/clist/get"

        response = requests.get(url, headers=headers, params=param)
        if response.status_code == 200:
            print(response.text)
        else:
            print("获取失败")
        response.close()


if __name__ == '__main__':
    gridlist=get_gridlist()
    get_data(get_cb(),get_wbp2u(),gridlist[0],gridlist[1])
